const Core = require("../../utils/core.js");
const ServiceAddress = require("../../service/service_address.js");
const BehaviorArea = require("./behavior-area.js");
const Tool = require("../../utils/tool.js");
const Validate = require("./validate.js");

module.exports = Behavior({
  /**
   * behaviors
   */
  behaviors: [BehaviorArea],
  /**
   * 页面的初始数据
   */
  data: {
    b_address_addressData: {
      id: null, username: '', phone: '', detailAddress: '', area: '', townId: null, defaultFlag: false 
    },
    b_address_addressEditData: {},
    b_address_addressEditShowFlag: false, // 显示编辑地址信息弹出框标致
    b_address_addressListData: [],
    b_address_addressListShowFlag: false,
    b_address_validate: null,
    /**
     * 对外接口
     */
    // 默认地址相关
    b_address_addressDefaultGainFlag: true,
    // 地址信息相关
    b_address_addressAddShowFlag: true,
    b_address_addressExistDefaultHideAddShowFlag: false,  // 如果为true，则有默认地址不显示新建地址按钮, 默认为false
    b_address_addressInfoShowFlag: true,
    b_address_addressInfoModifyShowFlag: true,
    b_address_addressInfoListShowFlag: true,
    // 地址服务相关
    b_address_addressServiceCreateFlag: false,
    b_address_addressServiceModifyFlag: false,
    b_address_addressServiceDeleteFlag: false,
    // 地址列表相关
    b_address_addressListStaticShowFlag: false,
    b_address_addressListSelectShowFlag: true,
    b_address_addressListEditShowFlag: true,
    b_address_addressListDeleteShowFlag: true,
    // 刷新地址列表相关
    b_address_addressListRefreshInitedFlag: false,
    b_address_addressListRefreshCreatedFlag: false,
    b_address_addressListRefreshModifiedFlag: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  ready: function (options) {
    const _this = this;
    // 实例化验证对象
    _this.b_address_validate = Validate.createInstance();
    // 获取默认地址数据
    if (_this.data.b_address_addressDefaultGainFlag){
      ServiceAddress.gainDefault(function (data) {
        if (data) {
          _this.setData({
            b_address_addressData: _this._assignAddressData(data)
          })
        }
        // 
        if (_this.data.b_address_addressExistDefaultHideAddShowFlag && data){
          _this.setData({ b_address_addressAddShowFlag: false });
        }
      });
    }
    // 
    if (_this.data.b_address_addressListRefreshInitedFlag){
      _this._listAddressService();
    }
  },
  /**
   * 方法
   */
  methods: {
    /**
     * [验证地址]数据 (为外部提供调用)
     */
    b_address_validateAddressData: function (e) {
      const _this = this;
      // 验证地址数据
      const addressShowData = _this.data.b_address_addressData;
      if (!_this.b_address_validate.checkForm(addressShowData)) {
        wx.showModal({
          content: _this.b_address_validate.errorList[0].msg,
          showCancel: false,
        });
        return false;
      }
      return true;
    },
    /**
     * 点击打开[新建地址]弹出框
     */
    b_address_onOpenAddressCreate: function (e) {
      const _this = this;
      //
      _this.setData({
        b_address_addressEditShowFlag: true,
        b_address_addressEditData: _this._initAddressData(),
        b_address_resetAreaFlag: true
      })
    },
    /**
     * 点击打开[修改地址]弹出框
     */
    b_address_onOpenAddressModify: function (e) {
      const _this = this;
      const showData = _this.data.b_address_addressData;
      //
      _this.setData({
        b_address_addressEditShowFlag: true,
        b_address_addressEditData: showData ? showData : {}
      })
    },
    /**
     * [关闭编辑地址]弹出框
     */
    b_address_onCloseAddressEdit: function () {
      const _this = this;
      _this.setData({
        b_address_addressEditShowFlag: false
      });
    },
    /**
     * [编辑]地址弹出框中的[输入内容]
     */
    addresss_onAddressEditInput: function (e) {
      const _this = this;
      const value = e.detail.value;
      const name = e.currentTarget.dataset.name;
      //
      _this.data.b_address_addressEditData[name] = value;
    },
    /**
     * [提交]地址弹出框中[编辑后的数据]
     */
    b_address_onSubmitAddressEdit: function (e) {
      const _this = this;
      const params = e.detail.value
      // 验证地址数据
      if (!_this.b_address_validate.checkForm(params)) {
        wx.showModal({
          content: _this.b_address_validate.errorList[0].msg,
          showCancel: false,
        });
        return false
      }
      // 处理数据
      _this.setData({
        b_address_addressData: params
      });
      // 处理服务
      const addressId = Core.toNumber(params.id);
      if (!isNaN(addressId)) {
        if (_this.data.b_address_addressServiceModifyFlag) {
          _this._editAddressService(addressId, params, function(){
            _this.setData({
              b_address_addressEditShowFlag: false
            })
            if (_this.data.b_address_addressListRefreshModifiedFlag) {
              _this._listAddressService();
            }
          });
        }else{
          _this.setData({
            b_address_addressEditShowFlag: false
          });
        }
      } else {
        if (_this.data.b_address_addressServiceCreateFlag){
          _this._addAddressService(params, function(){
            _this.setData({
              b_address_addressEditShowFlag: false
            })
            if (_this.data.b_address_addressListRefreshCreatedFlag) {
              _this._listAddressService();
            }
          });
        } else {
          _this.setData({
            b_address_addressEditShowFlag: false
          });
        }
      }
    },
    /**
     * [打开地址]列表
     */
    b_address_onOpenAddressList: function (e) {
      const _this = this;
      //
      _this._listAddressService();
    },
    /**
     * [选中地址]列表中指定地址
     */
    b_address_onSelectListAddress: function (e) {
      const _this = this;
      const id = e.currentTarget.dataset.id;
      //
      ServiceAddress.findById(id, function (data) {
        _this.setData({
          b_address_addressListShowFlag: false,
          b_address_addressData: _this._assignAddressData(data)
        })
      });
    },
    /**
     * [编辑地址]列表中指定地址
     */
    b_address_onEditListAddress: function(e){
      const _this = this;
      const id = e.currentTarget.dataset.id;
      const townid = e.currentTarget.dataset.townid;
      //
      ServiceAddress.findById(id, function (data) {
        _this.setData({
          b_address_addressEditShowFlag: true,
          b_address_addressEditData: _this._assignAddressData(data)
        })
      })
    },
    /**
     * [删除地址]列表中指定地址
     */
    b_address_onDeleteListAddress: function(e){
      const _this = this;
      const id = e.currentTarget.dataset.id;
      //
      if (_this.data.b_address_addressServiceDeleteFlag){
        _this._deleteAddressService(id);
      }else{
        _this._deleteListAddress(id);
      }
    },
    /**
     * [初始化地址]数据
     */
    _initAddressData: function () {
      return {
        id: null,
        username: '',
        phone: '',
        detailAddress: '',
        area: '',
        defaultFlag: false,
        townId: null
      }
    },
    /**
     * [赋值地址]数据
     */
    _assignAddressData: function (data) {
      return {
        id: data.id,
        username: data.username,
        phone: data.phone,
        detailAddress: data.detailAddress,
        area: data.area,
        defaultFlag: data.defaultFlag,
        townId: data.townId
      }
    },
    /**
     * [列出地址]服务
     */
    _listAddressService: function(){
      const _this = this;
      ServiceAddress.list(function (data) {
        const listData = [];
        for (let item of data.records) {
          listData.push(_this._assignAddressData(item));
        }
        _this.setData({
          b_address_addressListData: listData,
          b_address_addressListShowFlag: true
        })
      });
    },
    /**
     * [添加地址]服务
     */
    _addAddressService: function (params, callback) {
      ServiceAddress.add(params, function (data) {
        callback(data);
      });
    },
    /**
     * [编辑地址]服务
     */
    _editAddressService: function (id, params, callback) {
      ServiceAddress.edit(id, params, function (data) {
        callback(data);
      });
    },
    /**
     * [删除地址]服务
     */
    _deleteAddressService: function (id) {
      const _this = this;
      Tool.confirm("是否要删除地址?", function () {
        ServiceAddress.deleteById(id, function (data) {
          _this._deleteListAddress(id);
        });
      });
    },
    /**
     * 删除列表中地址项
     */
    _deleteListAddress: function(id){
      const _this = this;
      const addresses = _this.data.b_address_addressListData;
      for (let i in addresses) {
        const item = addresses[i]
        if (item.id === id) {
          addresses.splice(i, 1);
          _this.setData({
            b_address_addressListData: addresses
          })
          break;
        }
      }
    }

  }

})